#include "sComponent.h"
#include "sComponentInstance.h"
#include "sGui.h"

namespace sgui
{
namespace res
{

    void sComponent::load(db::Record &file)
    {
        sNamedObject::load(file);
		m_rect.load(file[L"rect"]);
		const db::Record &objects = file[L"rects"];
		for (u32 i = 0, t = objects.getSize(); i < t; i++)
		{
			sComponentRect::EComponentRectType type = (sComponentRect::EComponentRectType)objects[i].GetAsInt();

			sComponentRect *obj = sComponentRect::CreateComponentRect(type, getGui());
			obj->load(objects[i]);
			m_componentRects.push_back(obj);
		}
    }

    void sComponent::save(db::Record &file)
    {
		sNamedObject::save(file);
		file.Set(getClass());

		m_rect.save(file[L"rect"]);
		db::Record &objects = file[L"rects"];
		objects.setSize(m_componentRects.size());
		u32 idx = 0;
		for (std::deque<sComponentRect*>::const_iterator it = m_componentRects.begin(); it != m_componentRects.end(); it++)
		{
			(*it)->save(objects[idx++]);
		}
    }
	
    void sComponent::clear()
    {
		for (std::deque<sComponentRect*>::iterator it = m_componentRects.begin(); it != m_componentRects.end(); it++)
		{
			delete *it;
		}
		m_componentRects.clear();
		m_requiredRects.clear();
		m_rect.clear();
    }
    
    void sComponent::setRequiredRect(u32 idx, sComponentRect* rect)
    {
        if (idx < m_requiredRects.size())
        {
            if (rect->getClass() == m_requiredRects[idx].m_type)
            {
                m_requiredRects[idx].m_rect = rect;
            }
        }
    }

    bool sComponent::isValid() const
    {
        for (u32 i = 0; i < m_requiredRects.size(); ++i)
        {
            if (!m_requiredRects[i].m_rect)
            {
                return false;
            }
        }
        return true;
    }
    
    void sComponent::registerRequiredComponentRect(sComponentRect::EComponentRectType type)
    {
        m_requiredRects.push_back(sRequiredComponentRect(type));
    }
    
    void sComponent::init()
    {
        fillRequredRects();
    }

	sComponent::sComponent(sGUI& gui, const std::wstring& name):
		sNamedObject(gui, name)
    {

    }

	sComponent::~sComponent()
    {
		clear();
    }
};
};